<template>
  <div class="news-editor">
    <div class="logo">
      <img src="@/assets/image/logo.png" alt="logo"/>
      <span>陈陈每日新闻</span>
    </div>
    <div class="current-tab">
      <!-- 顶部切换 -->
      <div class="top">
        <div class="tab"
             :class="{ active: currentTab === 'news' }"
             @click="setCurrentTab('news')"> 新闻
        </div>
        <div class="tab" :class="{ active: currentTab === 'category' }"
             @click="setCurrentTab('category')">新闻类别
        </div>
        <div class="tab" :class="{ active: currentTab === 'video' }"
             @click="setCurrentTab('video')">视频
        </div>
      </div>
    </div>
    <van-form v-if="currentTab === 'news'" :model="newsForm" @submit="submitNewsForm">
      <van-cell-group inset>
        <van-field v-model="newsForm.title" label="新闻标题" :rule="newsRules.title" required/>
        <van-field v-model="newsForm.author" label="新闻作者" :rule="newsRules.author" required/>
        <van-field
            v-model="newsForm.category"
            is-link
            readonly
            name="picker"
            label="新闻类别"
            placeholder="点击选择新闻类别"
            @click="choiceNewsCategoryShowPicker = true"
            :rule="newsRules.category"
            required
        />
        <van-field label="新闻内容" required label-align="top">
          <template #input>
            <editor v-model:content="newsForm.content"/>
          </template>
        </van-field>
        <van-popup v-model:show="choiceNewsCategoryShowPicker" position="bottom">
          <van-picker
              :columns="choiceNewsCategoryColumns"
              @confirm="onConfirmChoiceNewsCategory"
              @cancel="choiceNewsCategoryShowPicker = false"
          />
        </van-popup>
        <imageUpload v-model:imageUrl="newsForm.imageUrl"/>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <van-form v-else-if="currentTab === 'category'" :model="newsCategoryForm" :rules="newsCategoryRules"
              @submit="submitNewsCategoryForm">
      <van-cell-group inset title="新增新闻列表">
        <van-field label-width="100px" v-model="newsCategoryForm.name" label="新闻类别名称" required
                   :rules="newsCategoryRules.name"/>
        <van-field label-width="100px" v-model="newsCategoryForm.description"
                   rows="2" type="textarea" maxlength="100"
                   show-word-limit autosize label="新闻类别描述" :rules="newsCategoryRules.description"/>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
      <!--已有的新闻类别-->
      <van-cell-group title="已有的新闻分类列表">
        <van-cell v-for="item in newsCategoryList" :key="item.id">
          <template #title>
            <van-icon name="delete" color="#fb3f63" @click.stop="deleteNewsCategoryItem(item.id)"/>
            <span class="custom-title">{{ item.name }}</span>
          </template>
          <template #value>
            <van-tag type="danger" v-if="item.description===''">暂无描述</van-tag>
            <van-tag type="primary" v-else>{{ item.description }}</van-tag>
          </template>
        </van-cell>
      </van-cell-group>
    </van-form>
    <van-form v-else-if="currentTab === 'video'" :model="videoForm" :rules="videoRules" @submit="submitVideoForm">
      <van-cell-group inset>
        <van-field v-model="videoForm.title" label="视频标题" required :rule="videoRules.title"/>
        <van-field v-model="videoForm.description" label="视频描述" required :rule="videoRules.description"/>
        <imageUpload :require="false" v-model:imageUrl="videoForm.imageUrl"/>
        <videoUpload v-model:videoUrl="videoForm.videoUrl"/>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import imageUpload from "@/components/Upload/imageLoad.vue";
import videoUpload from "@/components/Upload/videoLoad.vue";
import editor from "@/components/Editor/editor.vue";
import 'vant/es/dialog/style';
import {computed, onMounted, reactive, ref} from 'vue';
import {showConfirmDialog, showFailToast, showSuccessToast, showToast} from "vant";
import {createNewsCategory, deleteNewsCategory, getNewsCategory} from "@/api/news-category";
import {getUserRole} from "@/utils/userIsLogin";
import {createVideo} from "@/api/video";
import {createNews} from "@/api/news";

const newsForm = reactive({
  title: '',// 新闻标题
  content: '',// 新闻内容
  author: '',// 新闻作者
  category: '',// 新闻类别
  categoryId: '',// 新闻类别id
  imageUrl: '',// 新闻主图片
});
const newsRules = {
  title: [{required: true, message: '请输入新闻标题'}],
  author: [{required: true, message: '请输入新闻作者'}],
  category: [{required: true, message: '请选择新闻类型'}],
  image: [{required: true, message: '请上传新闻主图片'}],
};

const newsCategoryForm = reactive({
  name: '',
  description: '',
});
const newsCategoryRules = {
  name: [{required: true, message: '请输入新闻类别名称'}],
  description: [{required: false, message: '请输入新闻类别描述'}],
};
const videoForm = reactive({
  title: '',
  description: '',
  videoUrl: '',
  imageUrl: '',
});
const videoRules = {
  title: [{required: true, message: '请输入视频标题'}],
  description: [{required: true, message: '请输入视频描述'}],
  videoUrl: [{required: false, message: '请输入视频地址'}],
  imageUrl: [{required: false, message: '请输入视频封面地址'}],
};
const currentTab = ref('news');
const newsCategoryList = ref([]);//新闻类别列表
const choiceNewsCategoryShowPicker = ref(false);//选择新闻类别的弹窗
const setCurrentTab = (tab) => {
  currentTab.value = tab;
};

// 提交新闻
const submitNewsForm = async () => {
  if (!newsForm.title) {
    showToast('请输入新闻标题');
    return;
  }
  if (!newsForm.author) {
    showToast('请输入新闻作者');
    return;
  }
  if (!newsForm.category) {
    showToast('请选择新闻类别');
    return;
  }
  if (!newsForm.imageUrl) {
    showToast('请上传新闻主图片');
    return;
  }
  if (!newsForm.content) {
    showToast('请输入新闻内容');
    return;
  }
  console.log(newsForm);
  try {
    const result = await createNews(newsForm);
    if (result.msg !== '请求成功') {
      const msg = result.msg || '提交新闻失败，请重试';
      showFailToast(msg);
      return;
    }
    showSuccessToast('提交新闻成功');
    newsForm.title = '';
    newsForm.content = '';
    newsForm.author = '';
    newsForm.category = '';
    newsForm.categoryId = '';
    newsForm.imageUrl = '';
  } catch (error) {
    console.log(error, '<<<-----error')
    const msg = error.join(' ') || '提交新闻失败，请重试';
    showFailToast(msg);
    // showFailToast('提交新闻失败，请重试');
  }
};
// 获取新闻类别列表
const newsCategoryInit = async () => {
  try {
    newsCategoryForm.name = '';// 清空表单
    newsCategoryForm.description = '';// 清空表单
    const result = await getNewsCategory();
    if (result.msg !== '请求成功') {
      showFailToast('获取新闻类别列表失败，请重试');
      return;
    }
    newsCategoryList.value = result.data || [];
    console.log(newsCategoryList.value, '<<<-----newsCategoryList.value')
  } catch (error) {
    showFailToast('获取新闻类别列表失败，请重试');
  }
};
// 选择新闻类别
const choiceNewsCategoryColumns = computed(() => {
  if (newsCategoryList.value.length === 0) {
    return [];
  }
  return newsCategoryList.value.map(item => {
    return {
      text: item.name,
      value: item.id,
    };
  });
});
// 完成选择新闻类别
const onConfirmChoiceNewsCategory = ({selectedOptions}) => {
  newsForm.category = selectedOptions[0]?.text;
  newsForm.categoryId = selectedOptions[0]?.value;
  choiceNewsCategoryShowPicker.value = false;
};

onMounted(() => {
  newsCategoryInit();
});
// 提交新闻类别
const submitNewsCategoryForm = async () => {
  const role = getUserRole();
  if (role !== 'admin') {
    showFailToast('您没有权限添加新闻类别');
    currentTab.value = 'news';
    return;
  }
  try {
    const result = await createNewsCategory(newsCategoryForm);
    if (result.msg !== '请求成功') {
      showFailToast('添加失败，请重试');
      return;
    }
    showSuccessToast('添加成功');
    newsCategoryInit();
  } catch (error) {
    showFailToast('添加失败，请重试');
  }
};
// 删除新闻类别
const deleteNewsCategoryItem = (id) => {
  const role = getUserRole();
  if (role !== 'admin') {
    showFailToast('您没有权限删除新闻类别');
    currentTab.value = 'news';
    return;
  }
  showConfirmDialog({
    title: '提示',
    message: '确认删除该新闻类别吗？',
  }).then(async () => {
    try {
      const result = await deleteNewsCategory(id);
      console.log(result, '<<<-----result')
      if (result.msg !== '请求成功') {
        showFailToast('删除失败，请重试');
        return;
      }
      showSuccessToast('删除成功');
      await newsCategoryInit();
    } catch (error) {
      showFailToast('删除失败，请重试');
    }
  }).catch(() => {
    showToast('取消删除');
  });
};
// 提交视频
const submitVideoForm = async () => {
  if (!videoForm.title) {
    showToast('请输入视频标题');
    return;
  }
  if (!videoForm.description) {
    showToast('请输入视频描述');
    return;
  }
  if (!videoForm.videoUrl) {
    showToast('请上传视频');
    return;
  }
  if (!videoForm.imageUrl) {
    showToast('请上传视频封面');
    return;
  }
  console.log(videoForm);
  try {
    const result = await createVideo(videoForm);
    if (result.msg !== '请求成功') {
      showFailToast('添加失败，请重试');
      return;
    }
    showSuccessToast('添加视频成功');
    videoForm.title = '';
    videoForm.description = '';
    videoForm.videoUrl = '';
    videoForm.imageUrl = '';
  } catch (error) {
    showFailToast('添加视频失败，请重试');
  }
};

</script>

<style scoped lang="scss">
.news-editor {
  height: 100vh;
  width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  background-color: #f7f8fa;
  padding-top: 30px;

  .logo {
    margin-top: 50px;
    margin-bottom: 30px;
    width: 100%;
    height: 250px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    img {
      width: 300px;
      height: 150px;
      margin: 0 auto;
    }

    span {
      font-size: 72px;
      color: #8859c3;
      margin-top: 20px;
      font-weight: 600;
    }
  }

  .current-tab {
    padding: 20px;
    max-width: 750px;
    margin: 0 auto;

    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
    }

    .tab {
      flex: 1;
      text-align: center;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }

    .tab.active {
      color: #fff;
      background-color: #007aff;
    }

  }
}

.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
